<template>
  <el-dialog
    :title="type ? '换绑设备SN' : '绑定设备SN'"
    :visible.sync="dialogVisible"
    width="25%"
    center
    :close-on-click-modal="false"
    @close="closeDialog()"
  >
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="deviceSn" label-width="0px">
        <el-input v-model="form.deviceSn" maxLength="30" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog()">取 消</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { memberBindDev, isBindByDeviceSn } from "@/api/vip";
import { reject } from "lodash-es";
export default {
  data() {
    const validatorSN = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入SN码"));
      }
      if (!/^[A-Za-z0-9]{1,30}$/.test(value)) {
        return callback(
          new Error("请输入符合格式的SN码，仅支持最长30个数字、字母")
        );
      }
      setTimeout(async () => {
        let res = await isBindByDeviceSn({
          deviceSn: value,
          memberId: this.$route.query.memberId,
        });
        if (res?.data) {
          return callback(new Error("绑定失败，该设备SN已被绑定"));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      rules: {
        deviceSn: [{ validator: validatorSN, trigger: "blur" }],
      },
      dialogVisible: false,
      codeNo: "",
      form: {
        deviceSn: "",
      },
      type: false,
    };
  },
  methods: {
    open(type) {
      this.type = type;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let { deviceSn } = this.form;
          const params = {
            memberId: this.$route.query.memberId,
            deviceSn: deviceSn,
          };
          memberBindDev(params).then((res) => {
            if (res.code === 0) {
              this.$message({
                type: "success",
                message: `SN${this.type ? "换绑" : "绑定"}成功`,
              });
              this.closeDialog()
              this.$parent.fetchData()
            }
          });
        }
      });
    },
  },
};
</script>
